package com.definity.toolkit.i18n;

import java.net.MalformedURLException;
import java.util.Locale;

import com.definity.toolkit.ToolkitRuntimeException;

public class I18nFactory {

	protected static final I18nManager manager = I18nManager.getInstance();
	private static ClassLoader classLoader = I18nFactory.class.getClassLoader();

	static {
		getApplication();
	}
	
	private I18nFactory() {
		
	}
	
	public static void setClassLoader(ClassLoader classLoader) {
		I18nFactory.classLoader = classLoader;
	}

	public static final I18n getApplication() {
		return create(null, "application", Locale.getDefault());
	}

	public static final I18n getApplication(Locale locale) {
		return create(null, "application", locale);
	}
	
	public static final I18n create(String baseName) {
		return create(baseName, Locale.getDefault());
	}
	
	public static final I18n create(String baseName, Locale locale) {
		I18n i18n = manager.get(baseName);
		if (i18n == null) {
			i18n = create("application", baseName, locale);
		}
		return i18n;
	}
	
	public static final I18n create(String parentName, String baseName) {
		return create(parentName, baseName, Locale.getDefault());
	}
	
	public static final I18n create(String parentName, String baseName, Locale locale) {
		I18n parent = null;
		if (parentName != null) {
			parent = manager.get(parentName + locale.toString());
			if (parent == null) {
				if (parentName.equals("application")) {
					parent = getApplication(locale);
				} else {
					parent = create(parentName, locale);
				}
			}
		}
		I18n i18n = manager.get(baseName + locale.toString());
		if (i18n == null) {
			i18n = new I18n(classLoader, parent, baseName);
			try {
				i18n.load(locale);
			} catch (MalformedURLException e) {
				throw new ToolkitRuntimeException(e);
			}
			manager.add(baseName + locale.toString(), i18n);
		}
		return i18n;
	}

	public static final void remove(String baseName) {
		remove(baseName, Locale.getDefault());
	}
	
	public static final void remove(String baseName, Locale locale) {
		manager.remove(baseName + locale.toString());
	}
	
}
